#!/usr/bin/env node
var connect = require('../db/connect')
var crypto = require('crypto');
var connection = connect.connection;

module.exports.isNoRepeated = function(username){
    
    console.log('Username: '+username);
     connection.query(
                'select LoginName from Customer',
                function(err,rows){
                var bool;
                rows.forEach(function(e){    
                    if(e.LoginName === username){
                        console.log(username+' Repeated');
                        bool =  false;
                    }
                    });
                 bool= true;
                return bool;   
                });   
}

module.exports.getPassword = function(username){
    var pswd = '';
    var q = "select Password from Customer where LoginName = '"+username+"'"; 
     console.log('query: '+q);
     connection.query(q,
            function(err,results){
            pswd= results[0].Password;
            console.log('pswd_db:||'+pswd+'||');
            pswd = pswd.trim();
            pswd = md5(pswd);
            console.log('pw_db_md5: '+pswd);
            return pswd;
            });
   
   
     
     
}

module.exports.addUser = function(user){
    var username = user.username;
    var password = user.password;
    //TODO: combine user object with SQL insert.
    var q = "INSERT INTO `Customer` (`LoginName`,`Password`,`TrueName`,`Gender`,`Address`,`Postcode`,`Email`,`Phone`,`PswQuestion`,`PswAnswer`,`Account`) VALUES ('C000000001','Abel','lebA','Abel Tang','Male','Rua de Bruxelas edf Jardim Nam Ngon room G101 Macau','00853','dydeong@gmail.com','(00853)66669999','What''s my favority food?','Fish',10000.0);"
    var s = connection.query(q, error());
    console.log(s);
  //  connect.query;
}

var error = function(error){if(error) throw error;};

function md5(str) {
  var md5sum = crypto.createHash('md5');
  md5sum.update(str);
  str = md5sum.digest('hex');
  return str;
}

